<template>
  <div class="app-container">

    <!-- 查询部分 -->
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch">
      <el-form-item label="模板名称" prop="templateName">
        <el-input v-model="queryParams.templateName" placeholder="请输入模板名称" clearable style="width: 240px"
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="模板文件" prop="templateFile">
        <el-input v-model="queryParams.templateFile" placeholder="请输入模板文件名" clearable style="width: 240px"
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="模板代理端口" prop="templatePort">
        <el-input v-model="queryParams.templatePort" placeholder="请输入模板代理端口" clearable style="width: 240px"
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作按钮 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['mast:template:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate"
          v-hasPermi="['mast:template:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['mast:template:remove']">删除</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button type="warning" plain icon="Download" @click="handleExport"
          v-hasPermi="['mast:template:export']">导出</el-button>
      </el-col> -->
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 表格数据 -->
    <el-table v-loading="loading" :data="templateList" @selection-change="handleSelectionChange">
         <el-table-column type="selection" width="55" align="center" />
         <!-- <el-table-column label="角色编号" prop="templateId" width="120" /> -->
         <el-table-column label="模板名称" prop="templateName" :show-overflow-tooltip="true" width="200" />
         <el-table-column label="模板文件" prop="templateFile" :show-overflow-tooltip="true" width="350" />
         <el-table-column label="模板端口" prop="templatePort"  width="100" />
         <el-table-column label="更新时间" align="center" prop="updateTime">
            <template #default="scope">
               <span>{{ parseTime(scope.row.createTime) }}</span>
            </template>
         </el-table-column>
         <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
            <template #default="scope">
              <el-tooltip content="修改" placement="top" >
                <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['system:role:edit']"></el-button>
              </el-tooltip>
              <el-tooltip content="删除" placement="top">
                <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['system:role:remove']"></el-button>
              </el-tooltip>
            </template>
         </el-table-column>
      </el-table>



    <!-- 页码 -->
    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize" @pagination="getList" />

    <!-- 添加或修改角色配置对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="templateRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="模板名称" prop="templateName">
          <el-input v-model="form.templateName" placeholder="请输入模板名称" />
        </el-form-item>
        <el-form-item prop="templatePort">
          <template #label>
            <span>
              <el-tooltip content="模板中的代理端口，需不重复" placement="top">
                <el-icon><question-filled /></el-icon>
              </el-tooltip>
              模板端口
            </span>
          </template>
          <el-input v-model="form.templatePort" placeholder="请输入模板端口" />
        </el-form-item>
        <el-form-item  prop="templateFile">
          <template #label>
            <span>
              <el-tooltip content="模板文件，需手动上传" placement="top">
                <el-icon><question-filled /></el-icon>
              </el-tooltip>
              模板文件
            </span>
          </template>
          <template #default>
            <el-upload ref="upload" class="upload-demo" :action="uploadTemplateUrl" :limit="1" :headers="headers"
              :on-exceed="handleExceed" :on-success="handleSuccess" :on-error="handleError" :auto-upload="false">
              <template #trigger>
                <el-button type="primary">select file</el-button>
              </template>

              <el-button class="ml-3" type="success" @click="submitUpload" style="margin-left: 10px; margin-top: -3px;">
                upload to server
              </el-button>
              <template #tip>
                <div class="el-upload__tip text-red">
                  limit 1 file, new file will cover the old file
                </div>
              </template>
            </el-upload>
          </template>
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容"></el-input>
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>




  </div>

</template>


<script setup name="Template">
import { genFileId, ElMessage } from 'element-plus'
import { listTemplate, addTemplate, updateTemplate, deleteTemplate } from "@/api/mast/template";
import { ref } from 'vue';
import { getToken } from "@/utils/auth";

const headers = ref({ Authorization: "Bearer " + getToken() });
const uploadTemplateUrl = ref(import.meta.env.VITE_APP_BASE_API + "/mast/template/upload");

// 遮罩层
const loading = ref(true);
const { proxy } = getCurrentInstance();
//格式化数据
const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    templateName: undefined,
    templateFile: undefined,
    templatePort: undefined,
    
  },
  rules: {
    templateName: [{ required: true, message: "模板名称不能为空", trigger: "blur" }],
    templatePort: [{ required: true, message: "模板端口不能为空", trigger: "blur" }],
    templateFile: [{ required: true, message: "模板文件不能为空", trigger: "blur" }]
  },
});
const { queryParams, form, rules } = toRefs(data);
const templateList = ref([]);
const open = ref(false);
const title = ref("");
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(1);
const upload = ref(null);



/** 查询模板列表 */
function getList() {
  loading.value = true;
  listTemplate(queryParams.value).then(response => {
    templateList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  }
  );
}
/** 顶端查询 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 顶端查询重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryForm");
  handleQuery();
}

function reset() {
  form.value = {
    templateId: undefined,
    templateName: undefined,
    templatePort: undefined,
    templateFile: undefined,
    remark: undefined
  };
}

/** 多选框选中数据 */
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.templateId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加模板";
}
/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  if (row.templateId != undefined) {
    form.value = row;
  } else {
    const templateId = ids.value;
    const template = templateList.value.find(item => item.templateId === Number(templateId))
    form.value = template
  }
  open.value = true;
  title.value = "修改模板";
}
/** 删除按钮操作 */
function handleDelete(row){
  loading.value = true;
  const templateId = row.templateId || ids.value;
  deleteTemplate(templateId).then(response => {
      ElMessage.success('删除成功!');
      getList();
    });
    loading.value = false;

}

/** 对话框上传文件部分 */
const handleExceed = (files) => {
  upload.value.clearFiles()
  const file = files[0]
  file.uid = genFileId()
  upload.value.handleStart(file)
}

/** 新增窗口上传文件 */
const submitUpload = () => {
  upload.value.submit()
}


/** 新增窗口提交 */
function submitForm() {
  if (form.value.templateId != undefined) {
    updateTemplate(form.value).then(response => {
      ElMessage.success('修改成功!');
      open.value = false;
      getList();
    });
  } else {
    addTemplate(form.value).then(response => {
      ElMessage.success('新增成功!');
      open.value = false;
      getList();
    });
  }

}

/** 上传文件成功 */
function handleSuccess(response) {
  // 返回码是200，且code字段为成功，才视为上传成功
  if (response.code === 200) {
    form.value.templateFile = response.data;
    ElMessage.success('上传成功!');

  } else {
    upload.value.clearFiles()
    ElMessage.error(`上传失败: ${response.msg}`);
  }
}
function handleError(error, file, fileList) {
  upload.value.clearFiles()
  ElMessage.error(`上传失败: ${error.msg}`);
}

/** 取消按钮 */
function cancel() {
  open.value = false;
  reset();
  proxy.resetForm("templateRef");
}

getList();



</script>
